package cn.wps.sdk.demo.base;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.wps.sdk.demo.R;
import cn.wps.sdk.demo.util.FileCopyTool;
import cn.wps.sdk.demo.util.FileUtil;

public abstract class SingleSelectFileActivity extends Activity implements IAction{
    private FileAdapter mFileAdapter;
    private FileCopyTool mFileTool;
    private Button execute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_document);
        mFileTool = new FileCopyTool(this);
        ListView listView = findViewById(R.id.list);
        execute = findViewById(R.id.execute);
        execute.setText(executeName());
        mFileAdapter = new FileAdapter();
        listView.setAdapter(mFileAdapter);
        findViewById(R.id.execute).setOnClickListener(v -> {
            List<FileItem> fileSelectList = mFileAdapter.getData();
            List<FileItem> result = new ArrayList<>();
            for (FileItem fileSelect : fileSelectList) {
                if (fileSelect.isChecked) {
                    result.add(fileSelect);
                }
            }
            execute(result);
        });
        Button mSelectFileBtn = findViewById(R.id.select_file);
        mSelectFileBtn.setOnClickListener(v -> {
            selectFile();
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        refreshDocument();
    }

    private void refreshDocument() {
        List<File> list = mFileTool.getAllFile();
        List<FileItem> fileSelectList = new ArrayList<>();
        for (File file : list) {
            FileItem fileSelect = new FileItem();
            fileSelect.filePath = file.getAbsolutePath();
            fileSelect.isChecked = false;
            fileSelectList.add(fileSelect);
        }
        mFileAdapter.updateData(fileSelectList);
    }

    private void selectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, 1);
    }


    public static class ViewHolder {
        public RadioButton radioButton;
        public TextView text;
    }

    public static class FileAdapter extends BaseAdapter {

        private List<FileItem> mFiles;
        private WeakReference<RadioButton> mCheckedRadioButton = new WeakReference<>(null);

        public void updateData(List<FileItem> data) {
            if (mFiles == null) {
                mFiles = new ArrayList<>();
            } else {
                mFiles.clear();
            }
            mFiles.addAll(data);
            notifyDataSetChanged();
        }

        public List<FileItem> getData() {
            return mFiles;
        }

        @Override
        public int getCount() {
            return mFiles == null ? 0 : mFiles.size();
        }

        @Override
        public Object getItem(int position) {
            return mFiles == null ? null : mFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_document_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.text = view.findViewById(R.id.text);
                viewHolder.radioButton = view.findViewById(R.id.radio);
                view.setTag(viewHolder);
                convertView = view;
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            FileItem fileItem = mFiles.get(position);
            viewHolder.text.setText(FileUtil.getFileName(fileItem.filePath));
            viewHolder.radioButton.setChecked(fileItem.isChecked);
            viewHolder.radioButton.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
                fileItem.isChecked = isChecked;
                RadioButton checkedRadioButton = mCheckedRadioButton.get();
                if (checkedRadioButton != null && checkedRadioButton.isChecked()) {
                    checkedRadioButton.setChecked(false);
                }
                mCheckedRadioButton = new WeakReference<>((RadioButton) buttonView);
            });
            return convertView;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            List<Uri> pathList = new ArrayList<>();
            if (data.getData() != null) {
                try {
                    Uri uri = data.getData();
                    pathList.add(uri);
                } catch (Throwable ignore) {
                }
            } else {
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        Uri uri = item.getUri();
                        pathList.add(uri);
                    }
                }
            }
            mFileTool.copyFromManager(pathList);
            Toast.makeText(this, "copy success", Toast.LENGTH_SHORT).show();
            refreshDocument();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
